import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";

const foodsStore = createSlice({
    name: 'foods',
    initialState: {
        //商品列表
        foodsList: [],
        activeIndex: '',
        cartList: []
    },
    reducers: {
        //更改商品列表
        setFoodsList(state, action) {
            state.foodsList = action.payload
        },
        //更改activeIndex
        changeActiveIndex(state, action) {
            state.activeIndex = action.payload
        },
        //购物车
        addCart(state, action) {
            //是否添加过
            const item = state.cartList.find(item => item.id === action.payload.id)
            if (item) {
                item.count++
            } else {
                if (action.payload.count == null) {
                    action.payload.count = 1
                }
                state.cartList = [...state.cartList, action.payload]
            }
        },
        //购物车数量增
        increCount(state, action) {
            const item = state.cartList.find(item => item.id === action.payload.id)
            item.count++
        },
        //购物车数量减
        decreCount(state, action) {
            const item = state.cartList.find(item => item.id === action.payload.id)
            item.count--
            if (item.count <= 0) {
                state.cartList = state.cartList.filter(item => item.id !== action.payload.id)
            }
        },
        //清空购物车
        clearCart(state) {
            state.cartList = []
        }
    }
})

const { setFoodsList, changeActiveIndex, addCart, increCount, decreCount, clearCart } = foodsStore.actions
//异步获取商品
const fetchFoodsList = () => {
    return async (dispacth) => {
        const res = await axios.get("http://localhost:3004/takeaway")
        dispacth(setFoodsList(res.data))
        if (res.data != null && res.data.length > 0) {
            dispacth(changeActiveIndex(res.data[0].tag))
        } else {
            dispacth(changeActiveIndex(''))
        }
    }
}

export { fetchFoodsList, changeActiveIndex, addCart, increCount, decreCount, clearCart }

const reducer = foodsStore.reducer

export default reducer